package com.activiti.ActivitiUtils.impl;

import com.activiti.ActivitiUtils.bean.WrappedDeploymentBean;
import com.activiti.ActivitiUtils.factory.DeploymentBeanWrappedFactory;
import com.activiti.ActivitiUtils.runtime.WrappedDeploymentRuntime;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;
import java.util.zip.ZipInputStream;

/**
 * created by chongyahhh
 * 2020/4/4
 * 部署操作类
 */

@Component
public class WrappedDeploymentRuntimeImpl implements WrappedDeploymentRuntime {
    @Autowired
    private RepositoryService repositoryService;

    public WrappedDeploymentBean deploymentWithZip(String zipFileName,String deploymentName){
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("processes/" + zipFileName);
        ZipInputStream zipInputStream = new ZipInputStream(is);
        Deployment deployment = repositoryService.createDeployment()
                .addZipInputStream(zipInputStream)
                .name(deploymentName)
                .deploy();
        return DeploymentBeanWrappedFactory.inject(deployment);
    }

    public WrappedDeploymentBean deploymentWithBpmn(String bpmnFileName,String deploymentName){
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/" + bpmnFileName)
                .name(deploymentName)
                .deploy();
        return DeploymentBeanWrappedFactory.inject(deployment);
    }

    public void deleteProcessDefinition(String deploymentId){
        this.deleteProcessDefinition(deploymentId,false);
    }

    public void deleteProcessDefinition(String deploymentId,boolean cascade){
        repositoryService.deleteDeployment(deploymentId,cascade);
    }

    public InputStream getPngFile(String processDefinitionKey){
        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(processDefinitionKey)
                .list();
        ProcessDefinition processDefinition = processDefinitionList.get(0);
        if(processDefinition == null){
            return null;
        }
        String deploymentId = processDefinition.getDeploymentId();
        InputStream is = repositoryService.getResourceAsStream(deploymentId,processDefinition.getDiagramResourceName());
        return is;
    }
}
